package net.zjitc.servlet.file;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "DownLoadServlet",urlPatterns = "/downLoadServlet")
public class DownLoadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
     String path =   this.getServletContext().getRealPath("downloads/"+name);
        File file = new File(path);
        if (!file.exists()){
            PrintWriter writer = response.getWriter();
            writer.write("下载文件不存在");
        }else {
            response.setHeader("content-disposition","attachment;filename"+name);
            IOUtils.copy(new FileInputStream(file),response.getOutputStream());
        }

    }
}
